package com.elvt.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elvt.server.mapper.AdminMapper;
import com.elvt.server.mapper.AdminRoleMapper;
import com.elvt.server.mapper.RoleMapper;
import com.elvt.server.pojo.Admin;
import com.elvt.server.pojo.AdminRole;
import com.elvt.server.pojo.Menu;
import com.elvt.server.pojo.Role;
import com.elvt.server.service.IAdminService;
import com.elvt.server.utils.AdminUtil;
import com.elvt.server.utils.JwtTokenUtil;
import com.elvt.server.utils.RespSult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者：elvt
 * @since 2022-05-21
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登录之后返回token
     * @param username 用户名
     * @param password 密码
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespSult  login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("loginCodeRes");
        System.out.println(captcha);
            if (StringUtils.isEmpty(code) ||!code.equals(captcha)){
                return RespSult.error("验证码错误");
            }
        request.getSession().removeAttribute("loginCodeRes");
        UserDetails userDetails=null;
            try {
                userDetails = userDetailsService.loadUserByUsername(username);
            }catch (UsernameNotFoundException e){
                return RespSult.error("用户名或者密码不正确!!");
            }

        //判断用户名或者密码是否正确
        if (null==userDetails ||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespSult.error("用户名或者密码不正确!");

        }

        //判断账户状态是否开启
        if (!userDetails.isEnabled()){
            return RespSult.error("账户已经禁用，请联系管理员！！！");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //根据工具类拿到token
        String token = jwtTokenUtil.generateToken(userDetails);
        //将token和请求头返回给前段
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHeader",tokenHead);
        return RespSult.success("登录成功！",tokenMap);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }


    /**
     * 根据管理员id查询角色信息
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRolesByAdmin(Integer adminId) {
        return roleMapper.getRolesByAdmin(adminId);
    }

    /**
     *
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> findAllAdminByKeywords(String keywords) {

        return adminMapper.findAllAdmin(AdminUtil.getCurrentAdmin().getId(),keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId 操作员id
     * @param rids 角色id数组
     * @return
     */
    @Override
    @Transactional
    public RespSult updateAdminRole(Integer adminId, Integer[] rids) {
    adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));

        Integer row = adminRoleMapper.addAdminRole(adminId, rids);
        if (rids.length==row){
           return RespSult.success("修改成功！");

       }
        return RespSult.error("修改失败!");
    }

    @Override
    public RespSult updateAdminPassword(String oldPass, String pass, Integer adminId) {
        //拿到用户信息
        Admin admin = adminMapper.selectById(adminId);
        //判断旧密码是否正确
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())){
            //设置加密新密码
         admin.setPassword(encoder.encode(pass));
         if (adminMapper.updateById(admin)>0){
             return RespSult.success("更新成功！");
         }

        }
        return RespSult.error("更新失败！");
    }


}
